package com.example.forecastweather;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

import android.content.res.Resources.Theme;
import android.util.Log;

public class WeatherHttpClient {

	private static String URL_First = "http://api.openweathermap.org/data/2.5/forecast/daily?q=";
	private static String Image = "http://openweathermap.org/img/w/";

	// lay du lieu tu server
	public String getDataWeather(String location) {
		HttpURLConnection con = null;
		InputStream is = null;
		// thuc hien viec doc file
		try {
			// tao ket noi
			con = (HttpURLConnection) (new URL(URL_First + location))
					.openConnection();
			con.setRequestMethod("GET");
			con.setDoInput(true);
			con.setDoOutput(false);
			con.connect();

			// doc data
			StringBuffer buffer = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String contentLine = "";
			if ((contentLine = reader.readLine()) != null) {
				buffer.append(contentLine + "\r\n");
			}
			con.getInputStream().close();
			reader.close();
			con.disconnect();
			return buffer.toString();

		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				con.getInputStream().close();
			} catch (Throwable t) {
				t.printStackTrace();
			}
			try {
				con.disconnect();
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
		return null;
	}

	// lay anh icon tu server
	public byte[] getImage(String code) {
		HttpURLConnection con = null;
		InputStream is = null;

		// thuc hien doc
		try {
			con = (HttpURLConnection) (new URL(Image + code)).openConnection();
			con.setRequestMethod("GET");
			con.setDoInput(true);
			con.setDoOutput(false);
			con.connect();

			is = con.getInputStream();
			// khai bao mang byte de doc du lieu
			byte[] buffer = new byte[is.available()];
			if (is.read(buffer) != -1) {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bos.write(buffer);
				return bos.toByteArray();
			}

		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (Throwable t) {
			}
			try {
				con.disconnect();
			} catch (Throwable t) {
			}
		}
		return null;

	}
}
